﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace LitS3
{
    class CloudFrontAuthorizer
    {
        CloudFrontService service;
        HMACSHA1 signer;

        public CloudFrontAuthorizer(CloudFrontService service)
        {
            this.service = service;
            this.signer = new HMACSHA1(Encoding.UTF8.GetBytes(service.SecretAccessKey));
        }

        public static bool IsAuthorized(HttpWebRequest request)
        {
            return request.Headers[HttpRequestHeader.Authorization] != null;
        }

        /// <summary>
        /// Signs the given HttpWebRequest using the HTTP Authorization header with a value
        /// generated using the Amazon date header plus our SecretAccessKey.
        /// </summary>
        /// <remarks>
        /// See http://docs.amazonwebservices.com/AmazonCloudFront/2008-06-30/DeveloperGuide/RESTAuthentication.html
        /// </remarks>
        public void AuthorizeRequest(HttpWebRequest request)
        {
            string stringToSign = DateTime.UtcNow.ToString("r");
            request.Headers[S3Headers.AmazonDateHeader] = stringToSign;

            string signed = Sign(stringToSign);
            string authorization = string.Format("AWS {0}:{1}", service.AccessKeyID, signed);

            request.Headers[HttpRequestHeader.Authorization] = authorization;
        }

        string Sign(string stringToSign)
        {
            return Convert.ToBase64String(signer.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        }
    }
}
